import 'package:debounce_throttle/debounce_throttle.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

Throttle<T> useThrottle<T>(ValueChanged<T> callback, {required T initialValue, required Duration duration}) {
  return use(_ThrottleHook<T>(callback: callback, initialValue: initialValue, duration: duration ));
}

class _ThrottleHook<T> extends Hook<Throttle<T>> {
  const _ThrottleHook({
    required this.initialValue, 
    required this.callback,
    required this.duration
  });

  final T initialValue;
  final ValueChanged<T> callback;
  final Duration duration;

  @override
  HookState<Throttle<T>, Hook<Throttle<T>>> createState() {
    return _ThrottleHookState<T>();
  }
}

class _ThrottleHookState<T> extends HookState<Throttle<T>, _ThrottleHook<T>> {
  late Throttle<T> throttle;

  @override
  void initHook() {
    super.initHook();
    throttle = Throttle<T>(
      hook.duration,
      initialValue: hook.initialValue,
      onChanged: hook.callback
    );
  }

  @override
  Throttle<T> build(BuildContext context) {
    return throttle;
  }

  @override
  void dispose() {
    throttle.cancel();
    super.dispose();
  }
}
